package com.kuwei.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kuwei.utils.CommonUtils;
import com.kuwei.utils.Constants;

public class AuthFilter implements Filter{
	private String passUri = "public";
	private String redirectURL = null;
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		passUri = filterConfig.getInitParameter("passUri");
		redirectURL = filterConfig.getInitParameter("redirectURL");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;   
		HttpServletResponse resp = (HttpServletResponse) response;   
		HttpSession session = req.getSession(); 
		if(!checkUriIntercept(req.getRequestURI())&&CommonUtils.isEmpty(session.getAttribute(Constants.LOGIN_KEY))){
			 resp.sendRedirect(req.getContextPath()+ "/" + redirectURL);
			 return;
		} 
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		
	}
	
	/**
	 * 需要拦截的uri判读
	 * @param uri
	 * @return
	 */
	private boolean checkUriIntercept(String uri){
		boolean flag = false;
		for(String str : passUri.split(",")){
			flag = uri.indexOf(str)>-1;
			if(flag){
				break;
			}
		}
		return flag;
	}

}
